package cn.xiaolang.function.test_map;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 基于LinkedHashMap设计的LRUCache缓存（近期最少使用的删除）
 *
 * @author fuhw/Dean
 * @date 2020-03-20
 */
public class LRUCache<K, V> {

    private int capacity;
    private Map<K, V> cache;

    LRUCache(final int capacity) {
        this.capacity = capacity;
        // true 表示让 linkedHashMap 按照访问顺序来进行排序，最近访问的放在头部，最老访问的放在尾部
        this.cache = new LinkedHashMap<K, V>(capacity, 0.75f, true) {
            private static final long serialVersionUID = 1L;
            // 定义put后的移除规则，大于容量就删除eldest
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > capacity;
            }
        };
    }

    public V get(Object key) {
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else {
            return null;
        }
    }

    public void set(K key, V value) {
        cache.put(key, value);
    }

    @Override
    public String toString() {
        return "LRUCache [capacity=" + capacity + ", cache=" + cache + "]";
    }


}
